package com.sxjh.controller.ny;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sxjh.annotation.UserLog;
import com.sxjh.common.BaseController;
import com.sxjh.common.Result;
import com.sxjh.common.ResultException;
import com.sxjh.common.ZPage;
import com.sxjh.entity.DriverInfosEntity;
import com.sxjh.entity.WagonNumber;
import com.sxjh.entity.param.DriverInfoListParam;
import com.sxjh.enums.DelFlagEnum;
import com.sxjh.service.DriverInfosService;
import com.sxjh.service.WagonNumberService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * <p>
 * 司机信息表 前端控制器
 * </p>
 *
 * @author guanxy
 * @since 2023-05-29
 */
@Api(tags = "司机信息")
@RestController
@RequestMapping("/driverInfo")
public class DriverInfosController extends BaseController {


    @Autowired
    private DriverInfosService driverInfosService;

    @Autowired
    private WagonNumberService wagonNumberService;

    @ApiOperation("分页列表")
    @GetMapping(value = "/driverInfo.list")
    public Result<ZPage<DriverInfosEntity>> list(DriverInfoListParam param) {
        LambdaQueryWrapper<DriverInfosEntity> queryWrapper = new LambdaQueryWrapper();
        if (StrUtil.isNotBlank(param.getDriverName())) {
            queryWrapper.like(DriverInfosEntity::getDriverName, param.getDriverName());
        }
        if (StrUtil.isNotBlank(param.getDriverMobile())) {
            queryWrapper.like(DriverInfosEntity::getDriverMobile, param.getDriverMobile());
        }
        if (StrUtil.isNotBlank(param.getDriverIdentityCard())) {
            queryWrapper.like(DriverInfosEntity::getDriverIdentityCard, param.getDriverIdentityCard());
        }
        if (param.getDelFlag() != null) {
            queryWrapper.eq(DriverInfosEntity::getDelFlag, DelFlagEnum.NO.getType());
        }
        queryWrapper.orderByDesc(DriverInfosEntity::getId);
        Page<DriverInfosEntity> aPage = driverInfosService.page(new Page<>(param.getCurrent(), param.getSize()), queryWrapper);
        ZPage<DriverInfosEntity> zPage = copyPage(aPage, DriverInfosEntity::new);
        return Result.ok(zPage);
    }

    @ApiOperation("查询")
    @GetMapping(value = "/{id}")
    public Result<DriverInfosEntity> getById(@PathVariable("id") String id) {
        DriverInfosEntity driverInfosEntity = driverInfosService.getById(id);
        return Result.ok(driverInfosEntity);
    }

    @ApiOperation("新增")
    @PostMapping(value = "/add")
    @UserLog(desc = "内部倒运-新增司机", roleCode = "nbdy.driverInfo.add")
    public Result<Object> create(@RequestBody DriverInfosEntity params) throws ResultException {
        // 校验手机号码
//        String mobileInfo = checkMobileNumber(params.getDriverMobile());
        if (StrUtil.isBlank(params.getDriverMobile())) return err("司机联系方式不能为空");

        // 校验身份证号码
        String idCardInfo = checkIdentityCard(params.getDriverIdentityCard());
        if (StrUtil.isNotBlank(idCardInfo)) return err(idCardInfo);

        if (StrUtil.isNotBlank(params.getDriverName())) {
            LambdaQueryWrapper<DriverInfosEntity> query1 = new LambdaQueryWrapper<>();
            query1.eq(DriverInfosEntity::getDriverName, params.getDriverName());
            query1.eq(DriverInfosEntity::getDelFlag, DelFlagEnum.NO.getType());
            List<DriverInfosEntity> list = driverInfosService.list(query1);
            if (CollUtil.isNotEmpty(list)) {
                throw new ResultException(params.getDriverName() + "已存在");
            }
        }
        driverInfosService.save(params);
        return Result.ok(HttpStatus.OK);
    }

    /*public static String checkMobileNumber(String phone) {
        if(StrUtil.isNotBlank(phone) && phone.length() == 11) {
            String reExp = "^1[3456789]\\d{9}$";
            Pattern pattern = Pattern.compile(reExp);
            Matcher matcher = pattern.matcher(phone);
            if (!matcher.find()) {
                return "手机号码格式输入有误，请重新输入";
            }
        } else {
            return "手机号码格式输入有误，请重新输入";
        }
        return "";
    }*/

    private String checkIdentityCard(String idCard) {
        if (StrUtil.isNotBlank(idCard) && idCard.length() == 18) {
            Pattern p=Pattern.compile("(^[1-8][0-7]{2}\\d{3}([12]\\d{3})(0[1-9]|1[012])(0[1-9]|[12]\\d|3[01])\\d{3}([0-9Xx])$)");
            Matcher m = p.matcher(idCard);
            //匹配最后一位检验码是否正确
            int number[]= {7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2};
            //检验码对应规则，第三位实际上应该是x，这个地方用100但是实际上检验时不会用到
            int check[]= {1,0,100,9,8,7,6,5,4,3,2};
            if(m.matches())	{
                int sum=0;
                for(int i = 0;i < 17;i++) sum += number[i] * (idCard.charAt(i)-'0');
                sum %= 11;
                if(sum == 2 && ( idCard.charAt(17) == 'x'|| idCard.charAt(17) == 'X' )) {
                    return "";
                } else if(check[sum] == (idCard.charAt(17) - '0')) {
                    return "";
                } else {
                    return "身份证号码格式输入有误，请重新输入";
                }
            }
        } else {
            return "身份证号码格式输入有误，请重新输入";
        }
        return "";
    }

    @ApiOperation("删除")
    @GetMapping(value = "/delete/{id}")
    @UserLog(desc = "内部倒运-删除司机", roleCode = "nbdy.driverInfo.del")
    public Result<Object> delete(@PathVariable("id") String id) {
        int count = wagonNumberService.count(new LambdaQueryWrapper<WagonNumber>().eq(WagonNumber::getUnitId, id));
        if (count > 0) return Result.err("该承运单位在车辆管理中被使用了!");

        int count1 = wagonNumberService.count(
                new LambdaQueryWrapper<WagonNumber>()
                        .eq(WagonNumber::getDriverId, id));
        if (count1 > 0) return Result.err("该司机在车辆管理中被使用了");
        DriverInfosEntity params = new DriverInfosEntity();
        params.setId(Integer.valueOf(id));
        params.setDelFlag(DelFlagEnum.YES.getType());
        driverInfosService.updateById(params);
        return Result.ok(HttpStatus.OK);
    }

    @ApiOperation("修改")
    @PostMapping(value = "/update")
    @UserLog(desc = "内部倒运-修改司机", roleCode = "nbdy.driverInfo.update")
    public Result<Object> delete(@RequestBody DriverInfosEntity params) throws ResultException {
        if (StrUtil.isNotBlank(params.getDriverName())) {
            // 增加身份证校验逻辑
            String identityCard = checkIdentityCard(params.getDriverIdentityCard());
            if (StrUtil.isNotBlank(identityCard)) return Result.err(identityCard);

            LambdaQueryWrapper<DriverInfosEntity> query1 = new LambdaQueryWrapper<>();
            query1.eq(DriverInfosEntity::getDriverName, params.getDriverName());
            query1.eq(DriverInfosEntity::getDelFlag, DelFlagEnum.NO.getType());
            query1.ne(DriverInfosEntity::getId, params.getId());
            List<DriverInfosEntity> list = driverInfosService.list(query1);
            if (CollUtil.isNotEmpty(list)) {
                throw new ResultException(params.getDriverName() + "已存在");
            }
        }
        driverInfosService.updateById(params);
        return Result.ok(HttpStatus.OK);
    }

    @ApiOperation("启用/禁用")
    @GetMapping(value = "/activate")
    @UserLog(desc = "内部倒运-启禁用司机", roleCode = "nbdy.driverInfo.activate")
    public Result<Object> delete(@RequestParam("id") String id, @RequestParam("activateFlag") int activateFlag) {
        DriverInfosEntity params = new DriverInfosEntity();
        params.setId(Integer.valueOf(id));
        params.setActivateFlag(activateFlag);
        driverInfosService.updateById(params);
        return Result.ok(HttpStatus.OK);
    }

}
